package com.abhimanyu.bootstrap.readers;

import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.abhimanyu.dataaccess.GoogleDatastoreUsersDao;
import com.abhimanyu.dataaccess.model.User;
import com.google.appengine.api.datastore.Entity;

@Component
public class GoogleDatastoreRegisteredUsersReader implements ItemStream,
		ItemReader<User> {
	
	GoogleDatastoreUsersDao dao;
	Iterable<Entity> fetchedUsers;

	public void close() throws ItemStreamException {
		// TODO Auto-generated method stub

	}

	public void open(ExecutionContext arg0) throws ItemStreamException {
		fetchedUsers = dao.executeFetchAllUsers();
	}

	public void update(ExecutionContext executionContext)
			throws ItemStreamException {
		// TODO Auto-generated method stub
	}

	@Autowired
	public GoogleDatastoreRegisteredUsersReader(GoogleDatastoreUsersDao dao) {
		this.dao = dao;
	}

	public User read() throws Exception, UnexpectedInputException,
			ParseException, NonTransientResourceException {

		Entity userEntity = fetchedUsers.iterator().next();
		User user = dao.constructUser(userEntity);
		return user;
	}

}
